import re
from flask import current_app, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import db
from info.models import User
from info.modules.api_1_0 import login_blu


@login_blu.route("/login")
def login_index():

    return render_template("news/login.html")


@login_blu.route("/api/v1.0/session", methods=["POST"])
def login():
    # 获取参数
    dict_data = request.json
    mobile = dict_data.get("mobile")
    password = dict_data.get("password")

    if not re.match(r"1[35678]\d{9}", mobile):
        return jsonify(errno="4103", errmsg="请输入正确格式的手机号")

    if not all([mobile, password]):
        return jsonify(errno="4103", errmsg="请输入账号和密码")
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno="4001", errmsg="数据库查询错误")

    if not user:
        return jsonify(errno="4104", errmsg="用户没有注册")

    # if not user.check_passowrd(password):
    #     return jsonify(errno="4004", errmsg="密码输入错误")
    # user.password = "1111111"
    session["user_id"] = user.id
    #
    # try:
    #     db.session.add(user)
    #     db.session.commit()
    # except Exception as e:
    #     db.session.rollback()
    #     current_app.logger.error(e)
    #     return jsonify(errno="4001", errmsg="数据保存失败")
    session["user_id"] = user.id
    return jsonify(errno="0")
